package fm.yichenet.controller;

import fm.cache.AreaCache;
import fm.controller.BaseController;
import fm.entity.Address;
import fm.exception.BizException;
import fm.service.AddressService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by CM on 17/5/30.
 */
@Controller
@RequestMapping("/address")
public class AddressController extends BaseController {
    @Autowired
    AddressService addressService;

    /**
     * 获取区域列表
     * @param parentCode 顶级ID  省份的顶级为 100000
     * @return
     */
    @ResponseBody
    @RequestMapping("/list")
    public Map addressList(String parentCode) {
        Map res = new HashMap();
        try {
            List<Address> addresses = addressService.getByParentId(parentCode);
            res.put("data", addresses);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping("/getByNameOrCode")
    public Map getAddressByNameOrCode(String name,String code){
        Map res = new HashMap();
        try{
            if(StringUtils.isNoneBlank(code)){
                res.put("data",AreaCache.getAddress(code));
            }else if(StringUtils.isNotEmpty(name)){
                Address address = AreaCache.getAddressByName(name);
                if(address == null){
                    address = AreaCache.getAddressByShortName(name);
                }
                res.put("data",address);
            }
            this.success(res);
        }catch (BizException ex){
            LOGGER.error("occur business error",ex);
            this.failed(res,ex.getMessage());
        }catch (Exception ex){
            LOGGER.error("occur un-expected error",ex);
            this.failed(res,"服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }
}
